package cn.com.yusys.yusp.admin.service;

import cn.com.yusys.yusp.admin.domain.*;
import cn.com.yusys.yusp.admin.repository.mapper.AdminSmAuthRecoMapper;
import cn.com.yusys.yusp.admin.repository.mapper.AdminSmDataAuthMapper;
import cn.com.yusys.yusp.admin.repository.mapper.AdminSmRoleMapper;
import cn.com.yusys.yusp.admin.repository.mapper.AdminSmUserRoleRelMapper;
import cn.com.yusys.yusp.commons.mapper.CommonMapper;
import cn.com.yusys.yusp.commons.mapper.QueryModel;
import cn.com.yusys.yusp.commons.service.CommonService;
import cn.com.yusys.yusp.commons.util.DateUtil;
import cn.com.yusys.yusp.commons.web.rest.dto.ResultDto;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @项目名称：yusp-admin
 * @类名称：AcrmSmRoleService
 * @类描述：
 * @功能描述:
 * @创建人：zhanghan3@yusys.com.cn
 * @创建时间：2017-12-14 15:44
 * @修改备注：
 * @修改日期 修改人员 修改原因 -------- -------- ----------------------------------------
 * @version 1.0.0
 * @Copyright (c) 2017宇信科技-版权所有
 */
@Service
public class AdminSmRoleService extends CommonService {

	private static final Logger logger = LoggerFactory.getLogger(AdminSmInstuService.class);

	@Autowired
	private AdminSmDataAuthService dataAuthService;
	
	@Autowired
	private AdminSmRoleMapper mapper;

	@Autowired
	private AdminSmUserRoleRelMapper userMapper;
	
	@Autowired
	private AdminSmDataAuthMapper dataAuthMapper;
	
	@Autowired
	private AdminSmAuthRecoMapper authRecoMapper;

	@SuppressWarnings("rawtypes")
	@Override
	protected CommonMapper getMapper() {
		return this.mapper;
	}

	public AdminSmRoleService(AdminSmRoleMapper commonMapper) {
		super();
		this.mapper = commonMapper;
	}
	
	private final static String IDS = "ids";
	private final static String ROLE_ID = "roleId";
	private final static String LAST_CHG_USR = "lastChgUsr";
	private final static String LAST_CHG_DT = "lastChgDt";
	private final static int SUCCESS = 0;
	private final static int FAILED = -1;

	/**
	 * 分页查询
	 * 
	 * */
	@Transactional(readOnly = true)
	public List<Map<String, Object>> queryPage(QueryModel model) {
		// 设置分页查询参数(设置到线程变量中了)
		PageHelper.startPage(model.getPage(), model.getSize());
		List<Map<String, Object>> list = this.mapper.findAllByParam(model);
		PageHelper.clearPage();
		return list;
	}

	/**
	 * 
	 * 根据角色状态查询角色信息
	 * 
	 * @param <T>
	 * @param <T>
	 * @param orgInfo
	 * @return List
	 * */
	@Transactional(readOnly = true)
	public List<Map<String, Object>> getListByRolests(QueryModel model) {
		// 设置分页查询参数(设置到线程变量中了)
		PageHelper.startPage(model.getPage(), model.getSize());
		List<Map<String, Object>> list = this.mapper.findAllByRolests(model);
		PageHelper.clearPage();
		return list;
	}

	/**
	 * 新增角色下用户
	 */
	public int insert(Object record) {
		int n = 0;
		AdminSmUserRoleRel pool = (AdminSmUserRoleRel) record;
		pool.setLastChgDt(DateUtil.formatDateTimeByDef());// 最近跟新时间
		pool.setLastChgUsr("admin");
		// as.setUserId(userId);
		// as.setRoleId(did);
		this.insert(userMapper, pool);
		return n;

	}

	/**
	 * 新增角色
	 *
	 * */
	public ResultDto<Object> createRole(AdminSmRole pool) {
		String orgId = pool.getOrgId();
		int rd;
		rd = this.mapper.queryRoleLevel(orgId);
		pool.setRoleLevel(Integer.toString(rd));
		pool.setLastChgDt(DateUtil.formatDateTimeByDef());
		logger.info("New role data: [new role: {}] ",  pool.getRoleName());

		this.insertSelective(getMapper(), pool);
		String roleId = pool.getRoleId();
		ResultDto<Object> map = new ResultDto<Object>();
		map.setData(roleId);
		return map;
	}

	/**
	 * 修改角色
	 *
	 * */
	public int editRole(AdminSmRole pool) {
		String orgId = pool.getOrgId();
		int rd;
		rd = this.mapper.queryRoleLevel(orgId);
		pool.setRoleLevel(Integer.toString(rd));
		pool.setLastChgDt(DateUtil.formatDateTimeByDef());
		logger.info("Role modified data: [modified role: {} ", pool.getRoleName());
		return this.update(getMapper(), pool);
	}

	/**
	 * 
	 * @方法名称:deleteRole
	 * @方法描述:根据角色id删除角色
	 * @参数与返回说明:
	 * @算法描述:
	 */
	public Map<String, Object> deleteRole(String ids) {
	    int n=0;
        Map<String, Object> result = new HashMap<String, Object>();
        if (ids != null && !"".equals(ids.toString())) {
            String[] idStr = ids.split(",");
            int undelete = 0;
            for (int i = 0; i < idStr.length; i++) {
                if (!"".equals(idStr[i])) {
                    int userNum = this.mapper.getUserByRoleId(idStr[i]);
                    if(userNum>0){
                        undelete++;
                    }else{
                        n = n + this.mapper.deleteByPrimaryKey(idStr[i]);
                        logger.info("Delete role [PK: {}] ", idStr[i]);
                    }
                }
            }
            if(undelete==0){
                result.put("message", "成功删除" + n + "条数据!");
            }else{
                result.put("message", "成功删除" + n + "条数据,有" + undelete + "条数据由于关联角色数据，无法删除!");
            }
        }
		return result;
	}

	/**
	 *
	 * @方法名称:getRoleUser
	 * @方法描述:查询用户
	 * @参数与返回说明:
	 * @算法描述:
	 */
	@Transactional(readOnly = true)
	public List<Map<String, Object>> getRoleUser(QueryModel model) {
		PageHelper.startPage(model.getPage(), model.getSize());
		List<Map<String, Object>> list = mapper.getRoleUser(model);
		PageHelper.clearPage();
		return list;
	}

	/**
	 * 启用角色
	 * 
	 * @param id
	 * */
	public int useIngFn(String id, String userId, String date) {
		int n = 0;
		if (!"".equals(id)) {
			n = this.mapper.updateSts("A", id, userId, date);
		}
		return n;
	}

	/**
	 * 停用角色
	 * 
	 * @param id
	 * */
	public int unUseIngFn(String id, String userId, String date) {
		int n = 0;
		if (!"".equals(id)) {
			n = this.mapper.updateSts("I", id, userId, date);
		}
		return n;
	}

	/**
	 * 
	 * @方法名称: checkRoleCode
	 * @方法描述: 检查新增时角色编号是否重复
	 * @参数与返回说明:
	 * @算法描述:
	 */
	@Transactional(readOnly = true)
	public int createCheckrolecode(String roleCode) {
		return this.mapper.createCheckrolecode(roleCode);
	}

	/**
	 * 
	 * @方法名称: checkRoleCode
	 * @方法描述: 检查修改时角色编号是否重复
	 * @参数与返回说明:
	 * @算法描述:
	 */
	@Transactional(readOnly = true)
	public int editCheckrolecode(String roleCode, String roleId) {
		return this.mapper.editCheckrolecode(roleCode, roleId);
	}

	// 默认权限 begin add by chenlin
	/**
	 * 
	* @方法名称: getRoleAuthList
	* @方法描述: 查询默认权限
	* @参数与返回说明: 
	* @算法描述:
	 */
	public List<AdminSmAuthReco> getRoleAuthList(QueryModel model) {
		PageHelper.startPage(model.getPage(), model.getSize());
		List<AdminSmAuthReco> list = mapper.getRoleAuthList(model);
		PageHelper.clearPage();
		return list;
	}
	/**
	 * 
	* @方法名称: saveRoleAuth
	* @方法描述: 新增默认权限
	* @参数与返回说明: 
	* @算法描述:
	 */
	@Transactional(readOnly = false, rollbackFor = { Exception.class,
			RuntimeException.class })
	public int saveRoleAuth(AdminSmAuthReco pool) {
		//保存数据权限
		AdminSmDataAuth dataAuth = new AdminSmDataAuth();
		dataAuth.setAuthTmplId(pool.getAuthresId());
		dataAuth.setContrId("*");
		dataAuth.setLastChgUsr(pool.getLastChgUsr());
		dataAuth.setLastChgDt(DateUtil.formatDateTimeByDef());
		this.insert(this.dataAuthMapper, dataAuth);
		//保存资源对象授权记录
		pool.setAuthobjType("R");
		pool.setAuthresType("D");
		pool.setMenuId("*"); //默认权限设置菜单id为*
		pool.setAuthresId(dataAuth.getAuthId());
		pool.setLastChgDt(DateUtil.formatDateTimeByDef());
		return this.insert(this.authRecoMapper, pool);
	}
	/**
	 * 
	* @方法名称: updateRoleAuth
	* @方法描述: 修改默认权限
	* @参数与返回说明: 
	* @算法描述:
	 */
	public int updateRoleAuth(Map<String, String> paramMap){
		paramMap.put("lastChgDt", DateUtil.formatDateTimeByDef());
		mapper.updateRoleAuth(paramMap);
		return mapper.updateAuthReco(paramMap);
	}
	/**
	 * 
	* @方法名称: cleanRoleAuth
	* @方法描述: 清除角色默认权限
	* @参数与返回说明: 
	* @算法描述:
	 */
	public int cleanRoleAuth(String authId) {
		this.dataAuthService.deleteByPrimaryKey(authId);
		return mapper.cleanRoleAuth(authId);
	}
	// 默认权限 end

    /**
     *
     * @方法名称: getUserByRoleId
     * @方法描述: 角色停用前先查询是否有关联用户
     * @参数与返回说明:
     * @算法描述:
     */
    public int getUserByRoleId(String roleId){
        return this.mapper.getUserByRoleId(roleId);
    }
    
    /**
    *
    * @方法名称:addRoleUser
    * @方法描述:添加角色用户
    * @参数与返回说明:新增角色用户
    * @算法描述:
    */
   public ResultDto<Object> addRoleUser(Map<String, Object> param) {
	   ResultDto<Object> res=new ResultDto<Object>();
	   if (param.get(IDS) != null && param.get(ROLE_ID) != null) {
		   String [] ids = param.get(IDS).toString().split(",");
		   Map<String, Object> model=new HashMap<String,Object>();
		   model.put(IDS, ids);
		   model.put("roleId", param.get("roleId").toString());
		   List<Map<String, Object>> data=userMapper.queryRaleInfo(model);
		   if(null!=data && data.size()>0) {//判断关联信息是否已经存在
			   String mgs="";
			   for(int i=0;i<data.size();i++) {
				   Map<String, Object> info=data.get(i);
				   if(null!=info.get("userName")) {
					   mgs=mgs+"|"+info.get("userName")+"["+info.get("loginCode")+"]"+"|";
				   }else {
					   mgs=mgs+"|"+"无用户名"+"["+info.get("loginCode")+"]"+"|";
				   }
				   
			   }
			   res.setCode(-2);
			   res.setMessage(mgs);
		   }else {
			   for(int i=0;i<ids.length;i++) {
				   if(!"".equals(ids[i])) {
					   AdminSmUserRoleRel info =new AdminSmUserRoleRel();
					   info.setLastChgDt(DateUtil.formatDateTimeByDef());
					   info.setLastChgUsr(param.get("lastChgUsr").toString());
					   info.setRelSts("A");//默认生效
					   info.setRoleId(param.get("roleId").toString());
					   info.setUserId(ids[i]);
					   userMapper.insertSelective(info);
				   }
				   
			   }
			   res.setMessage("设置成功!");
		   }
	   } else {
		   res.setCode(-1);
		   res.setMessage("缺少参数信息,保存失败！");
	   }
	   return res;
   }
   
   /**
   *
   * @方法名称:delRoleUser
   * @方法描述:删除角色用户
   * @参数与返回说明:删除角色用户
   * @算法描述:
   */
   public int delRoleUser(Map<String, Object> param) {
	   if (param.get(IDS) != null && param.get(ROLE_ID) != null) {
		   String [] ids = param.get(IDS).toString().split(",");
		   param.replace(IDS, ids);
		   userMapper.delRoleUser(param);
		   return SUCCESS;
	   } else {
		   return FAILED;
	   }
   }
}
